// ./mongodb/manager/articleManager.js
const { ArticleModel: Article } = require("../../entity");

class ArticleManager {
  // 创建文章
  static async createArticle(data) {
    const article = new Article(data);
    return await article.save();
  }

  // 更新文章
  static async updateArticle(articleId, updateData) {
    return await Article.findByIdAndUpdate(articleId, updateData, {
      new: true,
    }).exec();
  }

  // 删除文章(标记删除)
  static async softDeleteUser(articleId) {
    return await Article.findByIdAndUpdate(
      articleId,
      { deleted: true },
      { new: true },
    ).exec();
  }

  // 删除文章(永久删除)
  static async deleteArticle(articleId) {
    return await Article.findByIdAndDelete(articleId).exec();
  }

  // 查找文章(根据文章 ID)
  static async getArticleById(articleId) {
    return await Article.findById(articleId).exec();
  }

  // 查找文章(根据文章标题)
  static async getArticleByTitle(title) {
    const article = await Article.findOne({ title, deleted: false }).exec();
    if (!article) {
      throw new Error("Article not found");
    }
    return article;
  }

  // 查找文章(获取所有未删除的文章)
  static async getAllActiveArticles() {
    return await Article.find({ deleted: false }).exec();
  }

  // 查找文章(根据 town 和 sort)
  static async getArticlesByTownAndSort(town, sort) {
    // 先查找所有符合 town 条件的文章
    let articles = await Article.find({ town, deleted: false }).exec();

    // 如果有 sort 参数，再进行进一步筛选
    if (sort) {
      articles = articles.filter((article) => article.sort === sort);
    }

    return articles;
  }
}

module.exports = { ArticleManager };
